﻿
Imports System.IO

Public Class errorpage
    Inherits requestProcessor
    'handle all kinds of error page

    Public Const errorfile As String = "static\errorpage.html"
    Public Const errorfile2 As String = "errorpage.html"
    Protected _errorpagebuff As bytes = Nothing

    Public Function errorpagebuff() As bytes
        Return _errorpagebuff
    End Function

    Public Overrides Function process(ByVal context As httpContext) As Boolean
        context.buff().Write(+_errorpagebuff, 0, _errorpagebuff.size())
        context.setstatuscode(Net.HttpStatusCode.OK, "NOTFOUND_Soft404_Error")
        context.setcontentType(network.http.contentType.texthtmlUtf8)
        context.setcontentEncoding(encoding.utf8)
        Return True
    End Function

    Public Overrides Function pathidentity() As String
        assert(False, "pathidentity should not be called in errorpage.")
        Return Nothing
    End Function

    Public Overrides Sub initial(Optional ByVal config As configParser = Nothing)
        MyBase.initial(config)
        On Error Resume Next
        If File.Exists(errorfile) Then
            _errorpagebuff = New bytes(File.ReadAllBytes(errorfile))
        ElseIf File.Exists(errorfile2) Then
            _errorpagebuff = New bytes(File.ReadAllBytes(errorfile2))
        Else
            _errorpagebuff = Nothing
        End If
        If _errorpagebuff Is Nothing OrElse _errorpagebuff.size() = 0 Then
            raiseError("cannot read errorfile " + errorfile + " or errorfile2 " + errorfile2 _
                       , errorHandle.errorType.warning)
            _errorpagebuff = New bytes(encoding.utf8.GetBytes("sorry, but " + applicationSign() _
                                                              + " cannot serve this page, ignore request."))
        End If
    End Sub

    Protected Shared _errorpage As errorpage = Nothing

    Public Shared Function errorpage() As errorpage
        If _errorpage Is Nothing Then
            _errorpage = New errorpage()
            _errorpage.initial()
        End If

        Return _errorpage
    End Function

    Public Shared Function processErrorPage(ByVal context As httpContext) As Boolean
        Return errorpage().process(context)
    End Function

#If RETIRED Then
    Protected Overrides Sub closeImpl()
        _errorpagebuff.clear()
        'i cannot remember why coding like this ~~
        'to avoid break other instances?
        Dim closedpage As errorpage = _errorpage
        _errorpage = Nothing
        If Not closedpage Is Nothing Then
            closedpage.close()
        End If
        MyBase.closeImpl()
    End Sub
#End If
End Class
